package com.ricky.constencrypt.demo

import android.util.Base64
import android.util.Log
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import kotlin.math.min


object AESUtil {
    private const val ALGORITHM = "AES"
    private lateinit var secretKey: SecretKeySpec

    fun setSecretKey(secretKey: String) {
        val keyBytes = ByteArray(32)
        val temp = secretKey.toByteArray(charset("UTF-8"))
        System.arraycopy(
            temp,
            0,
            keyBytes,
            0,
            min(temp.size.toDouble(), keyBytes.size.toDouble()).toInt()
        )
        this.secretKey = SecretKeySpec(keyBytes, ALGORITHM)
    }

    fun decrypt(encryptedData: String): String {
        val cipher = Cipher.getInstance(ALGORITHM)
        cipher.init(Cipher.DECRYPT_MODE, secretKey)
        val decryptedBytes = cipher.doFinal(Base64.decode(encryptedData, Base64.DEFAULT))
        return String(decryptedBytes, charset("UTF-8"))
    }
}